import React, { useState, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-components';
import { Card, Row, Col, Input, Tag, Typography, Space, Empty, Image, Button, message } from 'antd';
import { api } from '@/services/api';
import { Link, Category } from '@/services/generated/models';
import { SearchOutlined, StarOutlined, StarFilled } from '@ant-design/icons';
import './index.less'
const { Title, Paragraph } = Typography;
const { Meta } = Card;

const NavigationHome: React.FC = () => {
  const [categories, setCategories] = useState<Category[]>([]);
  const [links, setLinks] = useState<Link[]>([]);
  const [searchText, setSearchText] = useState('');
  const [loading, setLoading] = useState(false);
  const [visitingLinkId, setVisitingLinkId] = useState<number | null>(null);
  const [showOnlyFavorites, setShowOnlyFavorites] = useState(false);

  // 获取所有分类和链接
  const fetchData = async () => {
    setLoading(true);
    try {
      const [categoriesResponse, linksResponse] = await Promise.all([
        api.navigation.navigationCategoriesList({}),
        api.navigation.navigationLinksList({}),
      ]);
      setCategories(categoriesResponse || []);
      setLinks(linksResponse || []);
    } catch (error) {
      console.error('获取数据失败:', error);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchData();
  }, []);

  // 处理链接点击
  const handleLinkClick = async (link: Link) => {
    if (visitingLinkId === link.id) return;
    
    setVisitingLinkId(link.id);
    try {
      // 记录访问
      await api.navigation.navigationLinksVisitCreate({id: link.id});
      // 打开链接
      window.open(link.url, '_blank');
      // 刷新数据以更新访问次数
      fetchData();
    } catch (error) {
      console.error('记录访问失败:', error);
    } finally {
      setVisitingLinkId(null);
    }
  };

  // 处理收藏/取消收藏
  const handleToggleFavorite = async (e: React.MouseEvent, link: Link) => {
    e.stopPropagation(); // 阻止事件冒泡，避免触发链接点击
    try {
      await api.navigation.navigationLinksFavoriteCreate({ id: link.id });
      // message.success(link.isFavorited ? '已取消收藏' : '已添加收藏');
      // 刷新数据以更新收藏状态
      fetchData();
    } catch (error) {
      console.error('收藏操作失败:', error);
      message.error('操作失败，请重试');
    }
  };

  // 过滤链接
  const filteredLinks = links.filter(link => {
    // 首先过滤收藏
    if (showOnlyFavorites && !link.isFavorited) {
      return false;
    }
    // 然后过滤搜索文本
    if (!searchText) return true;
    const searchLower = searchText.toLowerCase();
    return (
      link.title?.toLowerCase().includes(searchLower) ||
      link.description?.toLowerCase().includes(searchLower) ||
      link.url?.toLowerCase().includes(searchLower) ||
      link.tags?.some(tag => tag.name.toLowerCase().includes(searchLower))
    );
  });

  // 按分类组织链接
  const linksByCategory = categories.map(category => ({
    category,
    links: filteredLinks.filter(link => link.category === category.id),
  }));

  return (
    <PageContainer
      header={{
        title: '导航主页',
      }}
    >
      <Card style={{ marginBottom: 24 }}>
        <Space style={{ marginBottom: 24, width: '100%', justifyContent: 'space-between' }}>
          <Input
            size="large"
            placeholder="搜索链接、标签或描述..."
            prefix={<SearchOutlined />}
            value={searchText}
            onChange={e => setSearchText(e.target.value)}
            style={{ width: 300 }}
          />
          <Button
            type={showOnlyFavorites ? "primary" : "default"}
            icon={<StarFilled />}
            onClick={() => setShowOnlyFavorites(!showOnlyFavorites)}
          >
            {showOnlyFavorites ? '显示全部' : '仅看收藏'}
          </Button>
        </Space>

        {linksByCategory.map(({ category, links }) => (
          links.length > 0 && (
            <div key={category.id} style={{ marginBottom: 24 }}>
              <Title level={4}>{category.name}</Title>
              <Row gutter={[16, 16]}>
                {links.map(link => (
                  <Col xs={24} sm={12} md={8} lg={6} key={link.id}>
                    <Card
                      hoverable
                      style={{ 
                        borderRadius: '12px',
                        overflow: 'hidden',
                        transition: 'all 0.3s',
                        opacity: visitingLinkId === link.id ? 0.7 : 1
                      }}
                      bodyStyle={{ 
                        padding: '16px',
                        background: '#f8f9fa'
                      }}
                      cover={link.icon && (
                        <div style={{ 
                          display: 'flex', 
                          justifyContent: 'center',
                          alignItems: 'center',
                          background: '#fff',
                          height: '140px',
                          width: '100%'
                        }}>
                          <Image
                            alt={link.title}
                            src={link.icon}
                            style={{ 
                              width: '100%',
                              height: '100%',
                              objectFit: 'cover',
                              display: 'block'
                            }}
                            rootClassName="custom-image"
                            preview={false}
                          />
                        </div>
                      )}
                      onClick={() => handleLinkClick(link)}
                      actions={[
                        <Button
                        type="text"
                        icon={link.isFavorited ? <StarFilled style={{ color: '#faad14' }} /> : <StarOutlined />}
                        onClick={(e) => handleToggleFavorite(e, link)}
                      >
                      </Button>
                      ]}
                    >
                      <Meta
                        title={
                          <div style={{ 
                            fontSize: '16px', 
                            fontWeight: 500,
                            marginBottom: '4px',
                            lineHeight: '22px',
                            display: 'flex',
                            justifyContent: 'space-between',
                            alignItems: 'center'
                          }}>
                            <span>{link.title}</span>
                            {link.visitCount > 0 && (
                              <Tag color="blue" style={{ marginLeft: 8, fontSize: '12px' }}>
                                {link.visitCount} 次访问
                              </Tag>
                            )}
                              
                          </div>
                        }
                        description={
                          <div style={{ 
                            color: '#666'
                          }}>
                            <Paragraph ellipsis={{ rows: 2 }} style={{ marginBottom: 8, fontSize: '14px' }}>
                              {link.description}
                            </Paragraph>
                            <div style={{ marginTop: '8px' }}>
                              {link.tags?.map(tag => (
                                <Tag key={tag.id} style={{ 
                                  margin: '0 8px 4px 0',
                                  background: '#e6f4ff',
                                  border: 'none',
                                  color: '#1677ff',
                                  borderRadius: '4px',
                                  padding: '2px 8px'
                                }}>
                                  {tag.name}
                                </Tag>
                              ))}
                            </div>
                          </div>
                        }
                      />
                    </Card>
                  </Col>
                ))}
              </Row>
            </div>
          )
        ))}

        {(!linksByCategory.some(({ links }) => links.length > 0)) && (
          <Empty description={
            <span>
              {showOnlyFavorites ? '暂无收藏的链接' : '没有找到匹配的链接'}
            </span>
          } />
        )}
      </Card>
    </PageContainer>
  );
};

export default NavigationHome;
